let logger = require("./Logger");

/**
 * 时间相关函数封装
 */
module.exports = {
    /**
     * 大麦相关服务
     */
    damai: {
        /**
         * 获取大麦网服务器时间
         * 如果出现异常则使用本地时间保底
         */
        getTime: () => {
            let result;
            try {
                const t = JSON.parse(http.get("https://mtop.damai.cn/gw/mtop.common.getTimestamp/", {
                    headers: {
                        'Host': 'mtop.damai.cn',
                        'Content-Type': 'application/json;charset=utf-8',
                        'Accept': '*/*',
                        'User-Agent': 'floattime/1.1.1 (iPhone; iOS 15.6; Scale/3.00)',
                        'Accept-Language': 'zh-Hans-CN;q=1, en-CN;q=0.9',
                        'Accept-Encoding': 'gzip, deflate, br',
                        'Connection': 'keep-alive'
                    }
                }).body.string()).data.t;
                result = parseInt(t);
            } catch (e) {
                logger.error("获取大麦时间戳失败...", e);
            }
            if (result && !isNaN(result)) return result;
            return Date.now();
        }
    },

    /**
     * 本地
     */
    local: {
        /**
         * 获取本地时间戳
         * @returns {number}
         */
        getTime: Date.now
    },

    /**
     * 时间戳转化为YYYY-MM-DD hh:mm:ss格式字符串
     * @param timestamp
     * @returns {`${number}-${string}-${string} ${string}:${string}:${string}`}
     */
    formatTimestamp: (timestamp) => {
        const date = new Date(timestamp);
        const pad = (n) => n.toString().padStart(2, '0');
        const year = date.getFullYear();
        const month = pad(date.getMonth() + 1); // 月份从0开始
        const day = pad(date.getDate());
        const hours = pad(date.getHours());
        const minutes = pad(date.getMinutes());
        const seconds = pad(date.getSeconds());
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    /**
     * 将YYYY-MM-DD hh:mm:ss格式的字符串转为Date对象
     * @param dateString
     * @returns {Date}
     */
    convertDate: (dateString) => {
        return new Date(dateString.replace(/-/g, '/'));
    },

    // /**
    //  * 等待指定毫秒
    //  * @param ms
    //  * @returns {Promise<unknown>}
    //  */
    // sleep: (ms) => {
    //     return new Promise(resolve => setTimeout(resolve, ms));
    // }
}